package com.linln.admin.util;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.*;

public class WXPayUtil {

    // 生成签名
    public static String generateSign(Map<String, String> params, String key) throws Exception {
        StringBuilder sb = new StringBuilder();
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        for (String k : keys) {
            if ("sign".equals(k) || StringUtils.isEmpty(params.get(k))) {
                continue;
            }
            sb.append(k).append("=").append(params.get(k)).append("&");
        }
        sb.append("key=").append(key);
        return MD5(sb.toString()).toUpperCase();
    }

    // MD5加密
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    // 解析微信回调的XML数据
    public static Map<String, String> parseXml(HttpServletRequest request) throws IOException, DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(request.getInputStream());
        Element root = document.getRootElement();
        Map<String, String> map = new HashMap<>();
        for (Iterator<Element> it = root.elementIterator(); it.hasNext(); ) {
            Element e = it.next();
            map.put(e.getName(), e.getText());
        }
        return map;
    }
}
